import json
import time


from numpy.ma.extras import average

from .gegtPublicData import *

#获取中心板块数据
# def getBaseData():
#     #先获取并打印
#     # cars = getAllCars()
#     car_messages = CarMessage.objects.all()
#     #传入列表
#     cars = list(getAllCars())
#     #车辆总数据
#     sumCar = len(cars)
#     #销量
#     highVolume = cars[0].sale
#     #车辆最高销售额
#     topCar = cars[0].brandName
#     #销售最多车型
#     carModels = {}
#     maxModel = 0
#     mostModel = ''
#     for car in cars:
#         if carModels.get(car.carModel,-1) == -1:
#             carModels[str(car.carModel)] = 1
#         else:
#             carModels[str(car.carModel)] += 1
#     # 对车型及其销售数量进行排序，按销售数量降序
#     carModels = sorted(carModels.items(), key=lambda x: x[1], reverse=True)
#
#     # 现在carModels[0][0]是销售最多的车型
#     if carModels:  # 确保carModels不为空
#         mostModel = carModels[0][0]  # 更新mostModel为销售最多的车型
#     # 打印销售最多的车型
#     # print(mostModel)
#
#     #品牌
#     carBrand = {}
#     maxBrand = 0
#     mostBrand = ''
#     for car in cars:
#         if carBrand.get(car.brandName,-1) == -1:
#             carBrand[str(car.brandName)] = 1
#         else:
#             carBrand[str(car.brandName)] += 1
#     for k,v in carBrand.items():
#         if v > maxBrand:
#             maxBrand = v
#             mostBrand = k
#     # print(mostBrand)
#
#     #车辆AVG
#     carPrice = {}
#     averagePrice = 0
#     sumPrice = 0
#     for carPrice in cars:
#         #最小
#         x = json.loads(carPrice.price)[0] + json.loads(carPrice.price)[1]
#         sumPrice += x
#         #最低最高价格相加，多了一倍。非只算最低/高
#     averagePrice = sumPrice / (sumCar * 2)
#     averagePrice = round(averagePrice, 2)
#     # print(sumCar, highVolume, topCar, mostModel, mostBrand, averagePrice)
#
#     car_dicts = [{
#         'sumCar':sumCar,
#         'highVolume':highVolume,
#         'topCar':topCar,
#         'mostModel':mostModel,
#         'mostBrand':mostBrand,
#         'averagePrice':averagePrice}  # 根据你的 CarMessage 模型调整字段
#         for car in car_messages
#     ]
#
#     print(sumCar, highVolume, mostBrand, mostModel, carPrice, averagePrice)
def getBaseData():
    cars = CarMessage.objects.all()
    sumCar = len(cars)

    if cars:
        #  sales 表销量，brandName 表品牌，carModel 表车型，price 是 JSON
        highVolume = max(cars, key=lambda cars: cars.sale).sale  # 销量最高的销量
        topCar = max(cars, key=lambda cars: cars.sale).seriesName  # 销量最高的车辆的品牌

        # 车型统计
        carModels = {}
        for car in cars:
            carModels[str(car.carModel)] = carModels.get(str(car.carModel), 0) + 1
        mostModel = max(carModels, key=carModels.get)  # 销售最多的车型

        # 品牌统计
        carBrand = {}
        for car in cars:
            carBrand[str(car.brandName)] = carBrand.get(str(car.brandName), 0) + 1
        mostBrand = max(carBrand, key=carBrand.get)  # 销售最多的品牌

        # 价格计算
        total_price = 0
        for car in cars:
            prices = json.loads(car.price)
            # 这里取平均价格（最低和最高价格的平均值）
            total_price += (prices[0] + prices[1]) / 2
        averagePrice = round(total_price / sumCar, 2)  # 平均价格

    else:
        highVolume, topCar, mostModel, mostBrand, averagePrice = None, None, None, None, 0

    print('数据:',sumCar,highVolume,topCar,mostModel,mostBrand, averagePrice)

    return {
        'sumCar': sumCar,
        'highVolume': highVolume,
        'topCar': topCar,
        'mostModel': mostModel,
        'mostBrand': mostBrand,
        'averagePrice': averagePrice
    }

##轮播
# def getRollList():
#     cars = list(getAllCars())
#     #品牌
#     carBrand = {}
#     for i in cars:
#         if carBrand.get(i.brandName,-1) == -1:
#             carBrand[str(i.brandName)] = 1
#         else:
#             carBrand[str(i.brandName)] += 1
#
#     brandList = [(value,key) for key,value in carBrand.items()]
#    # 进行排序
#     brandList = sorted(brandList,reverse=True)[:10]
#     sortDict = {car[1]: car[0] for car in brandList}
#     lastSortList = []
#     for k,v in sortDict.items():
#         lastSortList.append({
#             'name':k,
#             'value':v
#         })
#
#     # print(lastSortList)
#     print(sortDict)
#     return list(sortDict)
def getRollList():
    cars = list(getAllCars())
    if not cars:
        return []

    carBrand = {}
    for car in cars:
        carBrand[car.brandName] = carBrand.get(car.brandName, 0) + 1

        # 对品牌按出现次数降序排序，并取前10个
    brandList = sorted(carBrand.items(), key=lambda x: x[1], reverse=True)[:10]

    # 转换格式
    lastSortList = [{'name': name, 'value': count} for name, count in brandList]

    return lastSortList

#比率
def getTypeRate():
    cars = list(getAllCars())
    #能源类型
    carTypes = {}
    for car in cars:
        if carTypes.get(car.energyType,-1) == -1:
            carTypes[str(car.energyType)] =  1
        else:
            carTypes[str(car.energyType)] += 1
    #计算比率
    oilRate = round(carTypes['汽油'] / 525 * 100,2)
    electricRate = round(carTypes['纯电动'] / 525 * 100,2)
    mixRate = round(((525 - carTypes['汽油'] - carTypes['纯电动']) / 525 * 100),2)
    print(oilRate,electricRate,mixRate)
    return oilRate, electricRate, mixRate